package com.h3bpm.starcharge.service.impl.erp;

import OThinker.H3.Entity.DataModel.BizObject;
import OThinker.H3.Entity.Instance.Data.InstanceData;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.gson.Gson;
import com.h3bpm.starcharge.bean.k3c.LastNumber;
import com.h3bpm.starcharge.common.bean.BaseResult;
import com.h3bpm.starcharge.common.bean.JsonResult;
import com.h3bpm.starcharge.common.bean.RestfulErrorCode;
import com.h3bpm.starcharge.common.bean.RetResult;
import com.h3bpm.starcharge.common.uitl.FileUtil;
import com.h3bpm.starcharge.common.uitl.MapUtil;
import com.h3bpm.starcharge.common.uitl.OkHttpUtil;
import com.h3bpm.starcharge.common.uitl.k3c.K3cUtil;
import com.h3bpm.starcharge.config.ErpConfig;
import com.h3bpm.starcharge.config.K3CloundConfig;
import com.h3bpm.starcharge.ret.k3c.K3cBase;
import com.h3bpm.starcharge.service.erp.ErpGuestService;
import com.h3bpm.starcharge.service.k3c.BaseDataService;
import com.h3bpm.starcharge.service.k3c.K3cService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class ErpGuestServiceImpl implements ErpGuestService {

    @Autowired
    private K3cUtil util;
    @Autowired
    private K3cService k3cService;
    @Autowired
    private K3CloundConfig k3CloundConfig;
    @Autowired
    private BaseDataService baseDataService;

    @Value("${k3c_dbId}")
    private String dbId;
    @Value("${k3c_uid}")
    private String uid;
    @Value("${k3c_pwd}")
    private String pwd;
    @Value("${k3c_lang}")
    private int lang;
    @Value(value = "http://www.wbdhoa.com:8081/")
    private String golangApiUrl;

    private static final String STAR_CHARGE = "星充";
    private static final String FORM_ID = "BD_Customer";
    private static final String CONTACT_FORM_ID = "BD_CommonContact";


    /**
     * 保存
     * @param instanceData  InstanceData
     * @return RetResult
     */
    @Override
    public RetResult save(InstanceData instanceData) throws Exception {
        //得到流程信息
        HashMap<String, Object> valueTable = instanceData.getBizObject().getValueTable();
//        String number="";
        String cookie = util.getLoginCookie();
        /*// 保存联系人
        BizObject[] bizObjects = (BizObject[]) valueTable.get("guestLinkMan");
        if (null != bizObjects && bizObjects.length > 0) {
            RetResult retResult = saveContact(bizObjects, cookie);
            K3cBase base = (K3cBase) retResult.getData();
            number = base.getNumber();
        }*/

        //解析得到的流程信息，得到相应的值
        JSONObject basic = setSaveParam(valueTable);
        //调试输出值
        System.out.println(basic.toJSONString());
        //加入K3C保存时必填值(需要的值)
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("formid", FORM_ID);
        jsonObject.put("data", basic);
        // 禁止循环引用
        String param = JSON.toJSONString(jsonObject, SerializerFeature.DisableCircularReferenceDetect);

        // 保存
        RetResult result = k3cService.save(k3CloundConfig.getUrl() + k3CloundConfig.getSave(), cookie, param);
        //判断是否返回成功
        if (!RestfulErrorCode.SUCCESS.getCode().equals(result.getCode())) {
            return result;
        }
        K3cBase k3cBase = (K3cBase) result.getData();
        String submitParam = k3cService.buildParam(FORM_ID, k3cBase.getId(), null, null);
        // 提交
        k3cService.save(k3CloundConfig.getUrl() + k3CloundConfig.getSubmit(), cookie, submitParam);
        // 审核
        k3cService.save(k3CloundConfig.getUrl() + k3CloundConfig.getAudit(), cookie, submitParam);
        // 根据使用组织分配
        String useOrganization = (String) valueTable.get("useOrganization");
        JsonResult<List<BaseResult>> organizationList;
        StringBuilder sb = new StringBuilder();
        //得到是德和或星充的组织
        organizationList = baseDataService.getOrganizationBySql(STAR_CHARGE.equals(useOrganization) ? "FNUMBER like '102%'" : "FNUMBER = 101");
        List<BaseResult> data = organizationList.getData();
        for (BaseResult d : data) {
            sb.append(d.getValue()).append(",");
        }
        String orgStr = sb.toString();
        orgStr = orgStr.substring(0, orgStr.length() - 1);
        // 拼接分配参数
        String allocateParam = k3cService.buildAllocateParam(FORM_ID, orgStr, k3cBase.getId());
        k3cService.save(k3CloundConfig.getUrl() + k3CloundConfig.getAllocate(), cookie, allocateParam);
        // 保存联系人
        BizObject[] bizObjects = (BizObject[]) valueTable.get("guestLinkMan");
        if (null != bizObjects && bizObjects.length > 0) {
            RetResult retResult = saveContact(bizObjects, cookie);
            K3cBase base = (K3cBase) retResult.getData();
            String ids = base.getId();
            String number = ((K3cBase) result.getData()).getId();
            Map<String, String> map = new HashMap<>(4);
            map.put("ids", ids);
            map.put("number", number);
            OkHttpUtil.post(golangApiUrl + "Utils/contactBindCustomer", map);
        }
        return result;
    }
    /**
     * 保存联系人
     * @param zbBizObjects  BizObject[]
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    private RetResult saveContact(BizObject[] zbBizObjects, String cookie) throws Exception {
        // 解析json模板
        String template = FileUtil.readJsonData("k3c/contact-save-batch.json");
        JSONObject basic = JSON.parseObject(template);
        // 获取model数组
        JSONArray jsonArray = basic.getJSONArray("Model");
        Map<String, Object> modelTemplate = (Map<String, Object>) jsonArray.get(0);
        jsonArray.clear();
        for (BizObject zbBizObject : zbBizObjects) {
            setContactParam(modelTemplate, zbBizObject, jsonArray);
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("formid", CONTACT_FORM_ID);
        jsonObject.put("data", basic);
        // 禁止循环引用
        String param = JSON.toJSONString(jsonObject, SerializerFeature.DisableCircularReferenceDetect);
        // 保存
        return k3cService.save(k3CloundConfig.getUrl() + k3CloundConfig.getBatchSave(), cookie, param);
    }
    private void setContactParam(Map<String, Object> modelTemplate, BizObject zbBizObject, JSONArray jsonArray) throws Exception {
        Map<String, Object> newModel = new HashMap<>(32);
        newModel.putAll(modelTemplate);
        Map<String, Object> zbValueTable = zbBizObject.getValueTable();
        String[] keys = {"FNAME", "FMOBILE", "FCOMPANYTYPE"};
        String[] values = {"linkName", "linkPhone", "type"};
        MapUtil.batchSet(newModel, zbValueTable, keys, values);
        jsonArray.add(newModel);
    }

    private void setParam(JSONObject model, HashMap<String, Object> valueTable) throws Exception {
        if (null != valueTable.get("customerId")) {
            model.put("FCUSTID", valueTable.get("customerId"));
        }


        // 保存--获取最新的编码
        String customerCode = (String) valueTable.get("guestCode");
        if ("".equals(customerCode.trim())) {
            Map<String, String> postMap = new HashMap<>(2);
            postMap.put("group", (String) valueTable.get("guestGroupId"));
           // String json = OkHttpUtil.post(golangApiUrl + "customer/lastNumber", postMap);

            String json = OkHttpUtil.post(golangApiUrl + "Utils/lastNumber", postMap);
         //组合成LastNumber需要的值格式
            Gson gson = new Gson();
            Map<String, Object> remap = new HashMap<String, Object>();
            remap = gson.fromJson(json, remap.getClass());
            String fnumber=(String)remap.get("data");

            //LastNumber lastNumber = new Gson().fromJson(sdf, LastNumber.class);
            //valueTable.put("guestCode", lastNumber.getData().getFnumber());
            valueTable.put("guestCode", fnumber);
        }
        model.put("FNumber", valueTable.get("guestCode"));
        model.put("FName", valueTable.get("guestName"));
        // 国家
        Map<String, Object> country = new HashMap<>(4);
        country.put("FNumber", valueTable.get("country"));
        model.put("FCOUNTRY", country);
        String[] keys = {"FINVOICETITLE", "FTAXREGISTERCODE", "FINVOICEBANKNAME", "FINVOICETEL", "FINVOICEBANKACCOUNT", "FINVOICEADDRESS", "FADDRESS"};
        String[] values = {"invoiceRise", "taxRegistrationNumber", "bankOfDeposit", "invoiceTelephone", "bankAccount", "invoiceAddress", "customerAddress"};
        MapUtil.batchSet(model, valueTable, keys, values);
        // 客户分组
        Map<String, Object> group = new HashMap<>(4);
        group.put("FNumber", valueTable.get("guestGroupId"));
        model.put("FGroup", group);
        // 结算币别
        Map<String, Object> currency = new HashMap<>(4);
        currency.put("FNumber", valueTable.get("settlementCurrency"));
        model.put("FTRADINGCURRID", currency);
        // 结算方式
        Map<String, Object> clearType = new HashMap<>(4);
        clearType.put("FNumber", valueTable.get("settlementMethod"));
        model.put("FSETTLETYPEID", clearType);
        // 收款条件
        Map<String, Object> collection = new HashMap<>(4);
        collection.put("FNumber", valueTable.get("receivablesMethod"));
        model.put("FRECCONDITIONID", collection);
        model.put("FInvoiceType", valueTable.get("InvoiceType"));
        // 税分类
        Map<String, Object> taxType = new HashMap<>(4);
        taxType.put("FNumber", valueTable.get("taxType"));
        model.put("FTaxType", taxType);
        // 默认税率
        Map<String, Object> defaultTax = new HashMap<>(4);
        defaultTax.put("FNumber", valueTable.get("defaultRate"));
        model.put("FTaxRate", defaultTax);
        // 客户关联类型
        Map<String, Object> cognateType = new HashMap<>(4);
        cognateType.put("FNumber", valueTable.get("guestAssociationType"));
        model.put("F_WB_KHGLLX", cognateType);
        // 省市
        Map<String, Object> customerext = new LinkedHashMap<>(8);
        customerext.put("FEnableSL", false);
        Map<String, Object> province = new HashMap<>(4);
        province.put("FNumber", valueTable.get("province"));
        customerext.put("FPROVINCE", province);
        Map<String, Object> city = new HashMap<>(4);
        city.put("FNumber", valueTable.get("city"));
        customerext.put("FCITY", city);
        model.put("FT_BD_CUSTOMEREXT", customerext);
        // 银行信息
        List<Map<String, Object>> banks = new ArrayList<>();
        BizObject[] zbBizObjects = (BizObject[]) valueTable.get("guestBankInfo");
        if (null == zbBizObjects) {
            zbBizObjects = (BizObject[]) valueTable.get("guestBankInfoEdit");
        }
        if (null != zbBizObjects && zbBizObjects.length > 0) {
            for (BizObject object : zbBizObjects) {
                HashMap<String, Object> table = object.getValueTable();
                Map<String, Object> bank = new HashMap<>(8);
                if (null != table.get("bankId")) {
                    bank.put("FENTRYID", table.get("bankId"));
                }
                String[] key = {"FOPENBANKNAME", "FBANKCODE", "FACCOUNTNAME", "FOpenAddressRec"};
                String[] value = {"bank", "bankAccount", "accountName", "bankAddress"};
                MapUtil.batchSet(bank, table, key, value);
                Map<String, Object> bCurrency = new HashMap<>(4);
                bCurrency.put("FNumber", valueTable.get("bankCurrencyType"));
                bank.put("FCURRENCYID", bCurrency);
                bank.put("FISDEFAULT1", false);
                banks.add(bank);
            }
            model.put("FT_BD_CUSTBANK", banks);
        } else {
            model.put("FT_BD_CUSTBANK", banks);
        }
    }

    private JSONObject setSaveParam(HashMap<String, Object> valueTable) throws Exception {
        // 解析json模板
        String template = FileUtil.readJsonData("k3c/customer-save.json");
        JSONObject basic = JSON.parseObject(template);
        JSONObject model = basic.getJSONObject("Model");
        // 设置公共参数
        setParam(model, valueTable);
        return basic;
    }
//    private JSONObject setSaveParam(HashMap<String, Object> valueTable,String number) throws Exception {
//        // 解析json模板
//        String template = FileUtil.readJsonData("k3c/customer-save.json");
//        JSONObject basic = JSON.parseObject(template);
//        JSONObject model = basic.getJSONObject("Model");
//        //设置联系人编码
//        List<Map<String, Object>> linkMans = new ArrayList<>();
//        if (null != number && number.length()> 0) {
//
//            Map<String, Object> linkMan = new HashMap<>(8);
//            Map<String, Object> bCurrency = new HashMap<>(4);
//            bCurrency.put("FNUMBER", number);
//            linkMan.put("FContactId", bCurrency);
//            linkMan.put("FIsDefaultConsigneeCT", false);
//            linkMans.add(linkMan);
//
//            model.put("FT_BD_CUSTLOCATION", linkMans);
//        } else {
//            model.put("FT_BD_CUSTLOCATION", linkMans);
//        }
//
//        // 设置公共参数
//        setParam(model, valueTable);
//        return basic;
//    }

}
